import {
  areaList
} from '@vant/area-data';
var util = require('../../utils/util')
Page({
  data: {
    areaList,
    hide3: true,
    hide2: true,
    hide1: true,
    QRloading: false,
    QRshow: false,
    chooseCardType: false,
    chooseAddress: false,
    CardTypeColumns: [{
        text: '士官证',
        code: 1,
      },
      {
        text: '军官证',
        code: 2
      }, {
        text: '退伍证',
        code: 3
      }
    ],
    haveCard: false,
    reviewStatus: 0,
    fileList: [],
    applyInfo: {
      name: {
        value: '',
        error: false,
      },
      id_card_no: {
        value: '',
        error: false,
      },
      head_portrait: {
        option: 'header',
        value: '',
        error: false,
        errorMessage: '请上传真实头像'
      },
      contact_number: {
        value: '',
        error: false,
        errorMessage: '请输入您的联系电话'
      },
      army_papers_type: {
        text: '',
        value: '',
        error: false,
        errorMessage: '请选择您的证件类型'
      },
      army_papers_no: {
        value: '',
        error: false,
        errorMessage: '请输入您的证件号码'
      },
      contact_address: {
        value: '',
        error: false,
        errorMessage: '请填写或选择您的联系地址'
      },
    },
    expressInfo: {
      name: {
        value: "",
        error: false,
        errorMessage: '请输入您的姓名'
      },
      mobile: {
        value: "",
        error: false,
        errorMessage: '请输入您的联系电话'
      },
      address: {
        text: '',
        value: "",
        error: false,
        errorMessage: '请选择您的城市'
      },
      detail_address: {
        value: "",
        error: false,
        errorMessage: '请输入您的详细地址'
      },
    },
    stepsArr: [{
        text: '实名认证',
        inactiveIcon: 'certificate',
        activeIcon: '/images/steps/1r.png',
        toast: '您已完成实名认证'
      },
      {
        text: '完善资料',
        inactiveIcon: 'certificate',
        activeIcon: '/images/steps/2r.png',
        toast: '您已完善资料'
      },
      {
        text: '寄卡信息',
        inactiveIcon: 'certificate',
        activeIcon: '/images/steps/3r.png',
        toast: '您已提交过寄卡信息'
      },
      {
        text: '审核发卡',
        inactiveIcon: 'certificate',
        activeIcon: '/images/steps/4r.png',
      },
    ],
    AddressColumns: [{
        values: [],
        className: '省',
      },
      {
        values: [],
        className: '市',
      },
      {
        values: [],
        className: '县',
      },
    ]
  },
  overSize() {
    wx.showToast({
      title: '图片太大了,最大支持2M哦~',
      icon: 'none'
    })
  },
  deleteUpImg() {
    this.setData({
      [`applyInfo.head_portrait.fileList`]: [],
      [`applyInfo.head_portrait.value`]: '',
    })
  },
  beforeRead(e) {
    const {
      file,
      callback
    } = e.detail;
    // console.log(file.type)
    file.type === 'image' ?
      callback(true) :
      wx.showToast({
        title: '请选择图片文件',
        icon: 'none'
      })
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    wx.uploadFile({
      url: getApp().globalData.urls + 'api/image/upload',
      filePath: file.url,
      name: 'file',
      formData: {
        option: this.data.applyInfo.head_portrait.option
      },
      success: (res) => {
        // console.log(res)
        if (res.statusCode === 200) {
          let data = JSON.parse(res.data)
          // console.log(data)
          // 上传完成需要更新 fileList
          var fileList = []
          if (this.data.applyInfo.head_portrait.fileList) {
            fileList = this.data.applyInfo.head_portrait.fileList
          }
          fileList.push({
            ...file,
            url: getApp().globalData.urls + data.pic
          });
          this.setData({
            [`applyInfo.head_portrait.fileList`]: fileList,
            [`applyInfo.head_portrait.value`]: data.pic,
          });
          console.log(this.data.applyInfo.head_portrait)
        }
      }
    })
  },
  showTypePicker() {
    this.setData({
      chooseCardType: true
    })
  },
  addressOnChoosen(e) {
    //选择地址时，根据选中的选项发送请求
    // console.log(e)
    var index = e.detail.index;
    var code = e.detail.value[index].code
    // console.log(index, code);
    if (index <= 1) {
      this.setData({
        'addressLoading': true
      })
      //当修改的是省级/市级选项时，需要刷新下级菜单
      //获取下级菜单
      let url = index === 0 ? ('get/city?code=' + code) : ('get/area?code=' + code)
      util.sendRequest(url, 'GET').then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          let result = res.data.result
          this.setData({
            [`AddressColumns[${index+1}].values`]: result,
          })
          //修改的是省级菜单，那么还要获取再下一级菜单
          if (index === 0) {
            var code2 = result[0].code;
            // console.log(code2)
            util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
              if (res.data.code === 0) {
                let result = res.data.result;
                this.setData({
                  [`AddressColumns[2].values`]: result,
                  addressLoading: false,
                })
              }
            })
          } else {
            this.setData({
              'addressLoading': false
            })
          }
        }
      })
    }
  },
  chooseAddressShow() {
    // console.log('aaa')
    //获取默认显示的省市县信息，请求完成前显示加载画面
    this.setData({
      addressLoading: true
    })
    util.sendRequest('get/province', 'GET').then(res => {
      // console.log(res)
      if (res.data.code === 0) {
        let result = res.data.result;
        this.setData({
          [`AddressColumns[0].values`]: result,
          addressLoading: false,
        })
        var code1 = result[0].code
        util.sendRequest('get/city?code=' + code1, 'GET').then(res => {
          // console.log(res)
          if (res.data.code === 0) {
            let result = res.data.result;
            this.setData({
              [`AddressColumns[1].values`]: result,
            })
            var code2 = result[0].code;
            util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
              if (res.data.code === 0) {
                let result = res.data.result;
                this.setData({
                  [`AddressColumns[2].values`]: result,
                  addressLoading: false,
                })
              }
            })
          }
        })
      }
    })
    //弹出联系地址选项
    this.setData({
      chooseAddress: true
    })
  },
  addressConfirm(e) {
    // console.log(e.detail)
    let str = e.detail.value[0].name + e.detail.value[1].name + e.detail.value[2].name
    this.setData({
      'expressInfo.address.value': e.detail,
      'expressInfo.address.text': str,
    })
    this.onClose();
  },
  onClose() {
    this.setData({
      chooseCardType: false,
      chooseAddress: false,
      QRshow: false,
    })
  },
  CardTypeConfirm(e) {
    console.log(e.detail)
    this.setData({
      'applyInfo.army_papers_type.text': e.detail.value.text,
      'applyInfo.army_papers_type.value': e.detail.value.code,
      chooseCardType: false
    })
  },
  NextPage() {
    if (this.data.steps_v + 1 < this.data.stepsArr.length) {
      this.setData({
        steps_v: this.data.steps_v + 1
      })
    } else {
      wx.showToast({
        title: '这是最后一项',
        icon: 'none'
      })
    }
  },
  setStep(e) {
    console.log(e)
    let i = e.detail
    if (i < this.data.steps_v) {
      wx.showToast({
        title: this.data.stepsArr[i].toast,
        icon: 'none'
      })
    } else if (i > this.data.steps_v) {
      wx.showToast({
        title: '请先完成此步骤',
        icon: 'none'
      })
    }
    // this.setData({
    //   steps_v: e.detail
    // })
  },
  onCheckExpress() {
    var count = 0;
    let expressInfo = this.data.expressInfo;
    for (let key in expressInfo) {
      if (expressInfo[key].value) {
        count++
      } else {
        wx.showToast({
          title: expressInfo[key].errorMessage,
          icon: 'none'
        })
        this.setData({
          [`expressInfo.${key}.error`]: true
        })
        break;
      }
    }
    if (count === 4) {
      let data = {
        name: expressInfo.name.value,
        mobile: expressInfo.mobile.value,
        province_code: expressInfo.address.value.value[0].code,
        city_code: expressInfo.address.value.value[1].code,
        area_code: expressInfo.address.value.value[2].code,
        detail_address: expressInfo.detail_address.value,
      }
      console.log(data)
      util.sendRequest('rember/sendinfo', 'POST', data).then(res => {
        if (res.data.code === 0) {
          wx.showToast({
            title: '寄卡信息提交成功！',
            icon: 'none',
          })
          this.getApplyStatus()
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
        }
      })
    }
    //上传物流信息， 成功进入下一步
    // this.NextPage()
  },
  chooseLocation() {
    wx.getLocation({
      success: (res) => {
        // console.log(res)
        wx.chooseLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          success: (res) => {
            // console.log(res)
            this.setData({
              [`applyInfo.contact_address.value`]: res.address + res.name,
              [`applyInfo.contact_address.error`]: false,
            })
          }
        })
      }
    })
  },
  onCheckInfo() {
    // console.log(this.data.applyInfo)
    var num = 0
    for (let i in this.data.applyInfo) {
      if (i !== 'name' && i !== 'id_card_no') {
        if (!this.data.applyInfo[i].value) {
          wx.showToast({
            title: this.data.applyInfo[i].errorMessage,
            icon: 'none'
          })
          this.setData({
            [`applyInfo.${i}.error`]: true
          })
          break;
        } else {
          num++
        }
      }
    }
    // console.log(num)
    if (num === 5) {
      let applyInfo = this.data.applyInfo
      console.log(data)
      let data = {
        head_portrait: applyInfo.head_portrait.value,
        contact_number: applyInfo.contact_number.value,
        army_papers_type: applyInfo.army_papers_type.value,
        army_papers_no: applyInfo.army_papers_no.value,
        contact_address: applyInfo.contact_address.value,
      }
      util.sendRequest('rember/perfect/info', 'POST', data).then(res => {
        if (res.data.code === 0) {
          wx.showToast({
            title: '提交成功！',
            icon: 'none',
            success: () => {
              //完善资料验证，成功进入下一步
              this.NextPage()
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    }
  },
  // onCheckFace() {
  //   //人脸识别相关，调用人脸识别，成功的话进入下一步
  //   this.NextPage()
  // },
  fieldBlur(e) {
    console.log(e.currentTarget.dataset.key)
    // console.log(e)
    let key = e.currentTarget.dataset.key;
    let value = e.detail.value;
    let cursor = e.detail.cursor;
    if (cursor === 0) {
      this.setData({
        [`${key}.value`]: value,
        [`${key}.error`]: true
      })
    } else {
      this.setData({
        [`${key}.value`]: value,
        [`${key}.error`]: false,
      })
      // console.log(this.data.applyInfo)
    }
  },
  fieldFocus(e) {
    let key = e.currentTarget.dataset.key;
    this.setData({
      [`${key}.error`]: false,
    })
  },
  onSubmit() {
    //实名认证
    var applyInfo = this.data.applyInfo
    console.log(applyInfo)
    if (applyInfo.name.value && applyInfo.id_card_no.value) {
      let data = {
        id_card_no: applyInfo.id_card_no.value,
        name: applyInfo.name.value
      }
      util.sendRequest('rember/realname', 'POST', data).then(res => {
        console.log(res)
        if (res.data.code == -0) {
          //验证成功,进入下一步
          this.NextPage()
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '请输入姓名和身份证',
        icon: 'none'
      })
      this.setData({
        [`applyInfo.name.error`]: !applyInfo.name.value,
        [`applyInfo.id_card_no.error`]: !applyInfo.id_card_no.value,
      })
    }
  },
  getHeight(el) {
    //获取元素高度
    let query = wx.createSelectorQuery();
    query.select(el).boundingClientRect(rect => {
      let height = rect.height;
      // console.log(rect);
      this.setData({
        stepHeight: height
      })
    }).exec();
  },
  // changeReviewS() {
  //   if (this.data.reviewStatus === 0) {
  //     this.setData({
  //       reviewStatus: 2
  //     })
  //   } else {
  //     this.setData({
  //       reviewStatus: 0
  //     })
  //   }
  // },
  // haveCardTest() {
  //   this.setData({
  //     haveCard: !this.data.haveCard
  //   })
  // },
  changeHide(e) {
    // console.log(e)
    let item = e.currentTarget.dataset.value
    this.setData({
      [item]: !this.data[item]
    })
  },
  reApply() {
    //重新申请,回到第一步
    this.setData({
      steps_v: 0
    })
  },

  getCardInfo() {
    //获取会员卡信息
    //1，刷新用户信息，判断是否是会员
    util.sendRequest('get/userinfo', 'GET').then(res => {
      if (res.data.code === 0) {
        var userInfo = res.data.result
        this.setData({
          userInfo: userInfo
        })
        wx.setStorageSync('userInfo', userInfo);
        if (userInfo.is_soldier == 1) {
          //是会员
          this.setData({
            haveCard: true
          })
          //请求会员信息
          util.sendRequest('find/card/info', 'GET').then(res => {
            // console.log(res)
            if (res.data.code === 0) {
              let cardInfo = res.data.result;
              this.setData({
                cardInfo,
              })
              //获取消费信息
              util.sendRequest('monetary/info', 'GET').then(res => {
                if (res.data.code === 0) {
                  let result = res.data.result;
                  this.setData({
                    money: result.money,
                    monetary: result.monetary,
                  })
                }
              })
            }
          })
        } else {
          // 不是会员,查询状态
          this.getApplyStatus()
          this.setData({
            haveCard: false
          })
        }
      }
    })
  },
  ShowQR() {
    this.setData({
      QRshow: true,
      QRloading: true
    })
    //请求获取二维码, path 是商家扫码成功之后跳转的路径
    let data = {
      path: '/pages/ShopOwnerPages/QRMemberInfo/QRMemberInfo'
    }
    util.sendRequest('find/card/image', 'GET', data).then(res => {
      // console.log(res)
      if (res.data.code === 0) {
        this.setData({
          QRloading: false,
          QRimgInfo: res.data.result
        })
      } else {
        wx.showToast({
          title: res.data.msg,
        })
      }
    })

  },

  //获取请求情况
  getApplyStatus() {
    util.sendRequest('rember/audit/state', 'POST').then(res => {
      if (res.data.code === 0) {
        let result = res.data.result;
        console.log(result)
        if (result.audit_state == 0) {
          this.setData({
            steps_v: parseInt(result.step) - 1,
          })
        } else {
          // console.log('已申请')
          this.getServeTel()
          this.setData({
            steps_v: 3,
            reviewStatus: result.audit_state,
          })
          if (result.reject_reason) {
            this.setData({
              reject_reason: result.reject_reason
            })
          }
        }
        // console.log(this.data.steps_v)
      }
    })
  },
  getServeTel() {
    //获取服务电话
    util.sendRequest('service/info', 'GET').then(res => {
      if (res.data.code === 0) {
        this.setData({
          serveTel: res.data.result.tel
        })
      }
    })
  },
  onLoad: function (options) {
    this.setData({
      hoverHeight: getApp().globalData.windowHeight - getApp().globalData.navHeight,
      navHeight: getApp().globalData.navHeight,
      urls: getApp().globalData.urls,
    })
    this.getHeight('.step_hover')
    // console.log(this.data.hoverHeight)
    //判断用户是否已经拥有拥军卡并对 haveCard 赋值， 并判断显示 和获取信息
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCardInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})